package api

import (
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"github.com/jiedan/student-web/server/model"
)

// GetStudentSelections 获取当前学生的选课记录
func (h *CourseSelectionHandler) GetStudentSelections(c *gin.Context) {
	// 从上下文中获取当前用户ID
	userID, exists := c.Get("userID")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
		return
	}

	// 查找学生记录
	var student model.Student
	result := h.DB.Where("user_id = ?", userID).First(&student)
	if result.Error != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Student not found"})
		return
	}

	// 获取学生选课记录
	type CourseSelectionDetail struct {
		model.CourseSelection
		CourseName    string  `json:"course_name"`
		CourseID      string  `json:"course_id"`
		Credits       float64 `json:"credits"`
		TeacherName   string  `json:"teacher_name"`
		Semester      string  `json:"semester"`
		Description   string  `json:"description"`
	}

	var selections []CourseSelectionDetail
	result = h.DB.Table("course_selections").Select(
		"course_selections.*, courses.name as course_name, courses.course_id as course_id, courses.credits as credits, courses.semester as semester, courses.description as description, users.name as teacher_name",
	).Joins(
		"left join courses on course_selections.course_id = courses.id",
	).Joins(
		"left join teachers on courses.teacher_id = teachers.id",
	).Joins(
		"left join users on teachers.user_id = users.id",
	).Where(
		"course_selections.student_id = ?", student.ID,
	).Scan(&selections)

	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get course selections"})
		return
	}

	c.JSON(http.StatusOK, selections)
}

// GetAllSelections 获取所有选课记录（管理员和教师用）
func (h *CourseSelectionHandler) GetAllSelections(c *gin.Context) {
	// 分页参数
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "10"))
	offset := (page - 1) * pageSize

	// 获取选课记录总数
	var total int64
	h.DB.Model(&model.CourseSelection{}).Count(&total)

	// 获取选课记录
	type CourseSelectionDetail struct {
		model.CourseSelection
		StudentName  string  `json:"student_name"`
		StudentID    string  `json:"student_id"`
		Class        string  `json:"class"`
		CourseName   string  `json:"course_name"`
		CourseID     string  `json:"course_id"`
		Credits      float64 `json:"credits"`
		TeacherName  string  `json:"teacher_name"`
		Semester     string  `json:"semester"`
	}

	var selections []CourseSelectionDetail
	result := h.DB.Table("course_selections").Select(
		"course_selections.*, students.student_id as student_id, students.class as class, u1.name as student_name, courses.name as course_name, courses.course_id as course_id, courses.credits as credits, courses.semester as semester, u2.name as teacher_name",
	).Joins(
		"left join students on course_selections.student_id = students.id",
	).Joins(
		"left join users u1 on students.user_id = u1.id",
	).Joins(
		"left join courses on course_selections.course_id = courses.id",
	).Joins(
		"left join teachers on courses.teacher_id = teachers.id",
	).Joins(
		"left join users u2 on teachers.user_id = u2.id",
	).Limit(pageSize).Offset(offset).Scan(&selections)

	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get course selections"})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"total":      total,
		"page":       page,
		"page_size":  pageSize,
		"selections": selections,
	})
}

// GetCourseSelections 获取某课程的选课记录
func (h *CourseSelectionHandler) GetCourseSelections(c *gin.Context) {
	courseID, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid course ID"})
		return
	}

	// 检查课程是否存在
	var course model.Course
	result := h.DB.First(&course, courseID)
	if result.Error != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Course not found"})
		return
	}

	// 获取选课记录
	type StudentSelectionDetail struct {
		model.CourseSelection
		StudentName string `json:"student_name"`
		StudentID   string `json:"student_id"`
		Class       string `json:"class"`
		Email       string `json:"email"`
	}

	var selections []StudentSelectionDetail
	result = h.DB.Table("course_selections").Select(
		"course_selections.*, students.student_id as student_id, students.class as class, users.name as student_name, users.email as email",
	).Joins(
		"left join students on course_selections.student_id = students.id",
	).Joins(
		"left join users on students.user_id = users.id",
	).Where(
		"course_selections.course_id = ?", courseID,
	).Scan(&selections)

	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get course selections"})
		return
	}

	c.JSON(http.StatusOK, selections)
}